package com.xinrui.attendanceweb.service.impl;

import com.xinrui.attendanceweb.mapper.UserMapper;
import com.xinrui.attendanceweb.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    UserMapper userMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查找用户
        User user = userMapper.findByUsername(username);
        if(Objects.isNull(user)){
            throw new RuntimeException("账号或者密码错误");
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

        //赋予角色
        user.getRoleList().forEach(role -> {
            grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
        });
        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),grantedAuthorities);
    }


}
